<template>
  <el-affix 
    class="friends-affix" 
    :offset="20" 
    position="right" 
    target=".entertainment-app"
  >
    <div class="friends-container">
      <!-- 悬浮按钮 -->
      <el-badge 
        :value="unreadCount" 
        :hidden="unreadCount === 0" 
        type="danger"
      >
        <el-button 
          circle 
          type="primary" 
          icon="el-icon-chat-dot-round"
          @click="togglePanel"
          class="toggle-btn"
        ></el-button>
      </el-badge>
      <!-- 好友面板 -->
      <el-collapse-transition>
        <el-card 
          v-show="isExpanded" 
          class="friends-panel" 
          shadow="always"
        >
          <template #header>
            <div class="panel-header">
              <span>好友列表 ({{ filteredFriends.length }})</span>
              <div>
                <el-button
                  text
                  icon="el-icon-plus"
                  @click.stop="showAddDialog = true"
                ></el-button>
                <el-button 
                  text 
                  icon="el-icon-refresh" 
                  @click.stop="refreshList"
                />
                <el-button 
                  text 
                  icon="el-icon-close" 
                  @click.stop="togglePanel"
                />
              </div>
            </div>
          </template>

          <el-input
            v-model="searchQuery"
            placeholder="搜索好友"
            clearable
            prefix-icon="el-icon-search"
            @focus="autoExpand"
          />

          <el-scrollbar style="height: 60vh;">
            <el-empty 
              v-if="filteredFriends.length === 0" 
              description="暂无好友"
            />
            
            <div 
              v-for="friend in filteredFriends" 
              :key="friend.id"
              class="friend-item"
              :class="{ 'online': friend.isOnline }"
            >
              <el-popover
                placement="left"
                :width="200"
                trigger="hover"
              >
                <template #reference>
                  <div class="friend-content" @click="selectFriend(friend)">
                    <el-avatar :size="40" :src="friend.avatar" />
                    <div class="friend-info">
                      <span class="name">{{ friend.name }}</span>
                      <el-tag 
                        v-if="friend.status" 
                        :type="getStatusType(friend.status)"
                        size="small"
                        effect="plain"
                      >
                        {{ friend.statusText }}
                      </el-tag>
                    </div>
                  </div>
                </template>
                <div class="friend-actions">
                  <el-button 
                    type="primary" 
                    size="small" 
                    icon="el-icon-chat-dot-round" 
                    @click="startChat(friend)"
                  >
                    聊天
                  </el-button>
                  <el-button 
                    type="info" 
                    size="small" 
                    icon="el-icon-user" 
                    @click="viewProfile(friend)"
                  >
                    资料
                  </el-button>
                </div>
              </el-popover>
            </div>
          </el-scrollbar>
        </el-card>
      </el-collapse-transition>
    </div>

    <!-- 添加好友对话框 -->
    <el-dialog
      title="添加好友"
      :visible.sync="showAddDialog"
      width="320px"
    >
      <el-form :model="addForm" label-width="60px">
        <el-form-item label="账号">
          <el-input v-model="addForm.friendId" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleAddFriend">确 定</el-button>
      </div>
    </el-dialog>
  </el-affix>
</template>

<script>
import { getFriendList,addFriend } from '@/api/user'

export default {
  name: 'FriendsList',
  props: {
    initialFriends: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isExpanded: false,
      searchQuery: '',
      friends: [],
      unreadCount: 0,
      showAddDialog: false,
      addForm: {
        friendId: ''
      }
    }
  },
  computed: {
    filteredFriends() {
      const query = this.searchQuery.toLowerCase()
      return this.friends.filter(f => 
        (f.name && f.name.toLowerCase().includes(query)) ||
        (f.remark && f.remark.toLowerCase().includes(query))
      )
    }
  },
  created() {
    this.friends = [...this.initialFriends]
    this.getUserFriendList()
  },
  methods: {
    /**
     * 获取用户好友列表
     */
    async getUserFriendList() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      const userId = userInfo.userid
      if (userId) {
        try {
          const res = await getFriendList(userId)
          // 根据后端返回结构调整
          this.friends = res.data || res.friends || []
        } catch (e) {
          this.$message && this.$message.error('获取好友列表失败')
        }
      }
    },
    //添加好友
    async handleAddFriend() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const userId = userInfo.userid
        if (!this.addForm.friendId) {
        this.$message.warning('请输入好友账号')
        return
        }
        try {
        await addFriend(userId, this.addForm.friendId)
        this.$message.success('添加好友请求已发送')
        this.showAddDialog = false
        this.addForm.friendId = ''
        this.getUserFriendList()
        } catch (e) {
        this.$message.error('添加好友失败')
        }
    },
    togglePanel() {
      this.isExpanded = !this.isExpanded
      if (this.isExpanded && this.unreadCount > 0) {
        this.clearUnread()
      }
    },
    autoExpand() {
      if (!this.isExpanded) {
        this.isExpanded = true
      }
    },
    refreshList() {
      this.getUserFriendList()
      this.$emit('refresh-request')
    },
    selectFriend(friend) {
      this.$emit('friend-selected', friend)
    },
    startChat(friend) {
      this.$emit('start-chat', friend)
    },
    viewProfile(friend) {
      // 可扩展为查看资料功能
      this.$emit('view-profile', friend)
    },
    clearUnread() {
      this.unreadCount = 0
      this.$emit('clear-unread')
    },
    getStatusType(status) {
      const map = {
        online: 'success',
        busy: 'warning',
        offline: 'info'
      }
      return map[status] || 'info'
    },
    // 可暴露给父组件的方法
    addNewFriend(friend) {
      this.friends.unshift(friend)
    },
    updateFriendStatus(id, status) {
      const friend = this.friends.find(f => f.id === id)
      if (friend) {
        friend.isOnline = status === 'online'
        friend.status = status
      }
    },
    incrementUnread() {
      this.unreadCount++
    },
    handleAddFriend() {
      const friendId = this.addForm.friendId.trim()
      if (!friendId) {
        this.$message.warning('请输入好友账号')
        return
      }
      // TODO: 调用添加好友接口
      this.$message.success(`已发送添加好友请求给 ${friendId}`)
      this.showAddDialog = false
      this.addForm.friendId = ''
    }
  }
}
</script>

<style scoped>
.friends-affix {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1000;
}

.friends-container {
  display: flex;
  align-items: flex-start;
}

.toggle-btn {
  width: 48px;
  height: 48px;
  font-size: 18px;
  box-shadow: var(--el-box-shadow-light);
}

.friends-panel {
  width: 280px;
  margin-left: 12px;
  border-radius: 8px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 8px;
}

.friend-item {
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-light);
  transition: background 0.3s;
}

.friend-item:hover {
  background: var(--el-color-primary-light-9);
}

.friend-item.online .name {
  color: var(--el-color-primary);
}

.friend-content {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
}

.friend-info {
  margin-left: 12px;
  display: flex;
  flex-direction: column;
}

.name {
  font-size: 14px;
  margin-bottom: 4px;
  font-weight: 500;
}

.friend-actions {
  display: flex;
  justify-content: space-around;
  padding: 8px 0;
}

/* 动画效果 */
.el-collapse-transition-enter-active,
.el-collapse-transition-leave-active {
  transition: all 0.3s ease;
}

.el-collapse-transition-enter-from,
.el-collapse-transition-leave-to {
  opacity: 0;
  transform: translateX(20px);
}
</style>